package com.example.demo.controller;

import com.example.demo.pojo.Result;
import com.example.demo.pojo.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtil;
import com.example.demo.utils.Md5Util;
import com.example.demo.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired

    private StringRedisTemplate stringRedisTemplate;
    @PostMapping("/register")
    public Result register(@Pattern(regexp="^\\S{5,16}$")String username, @Pattern(regexp="^\\S{5,16}$") String password) {
        //查询数据库是否有用户
        User user = userService.findByUserName(username);
        //不存在，注册
        if(user==null){
            userService.register(username,password);
            return Result.success();
        }
        return Result.error("用户名已经被占用");


    }
    @PostMapping("/login")
    public Result login(@Pattern(regexp="^\\S{5,16}$")String username, @Pattern(regexp="^\\S{5,16}$") String password){
        //查询数据库，根据用户名查询
        User user=userService.findByUserName(username);

        //判断用户是否存在，
        if(user==null){
            return Result.error("用户名错误");
        }
        //判断密码是否正确
        if(user.getPassword().equals(Md5Util.getMD5String(password))){
            //登录成功
            Map<String,Object> claims =new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",user.getUsername());
            String token = JwtUtil.genToken(claims);
            //把令牌存储到redis
            ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }
    //获取用户详细信息
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name="Authorization")String token*/){
        /*Map<String,Object> map=JwtUtil.parseToken(token);*/
        //查询用户的信息
        Map<String,Object> map= ThreadLocalUtil.get();
        User user = userService.findByUserName((String) map.get("username"));
        return Result.success(user);
    }
    //更新用户信息
    @PutMapping("/update")
    public Result update(@RequestBody User user){
        userService.update(user);
        return Result.success();
    }
    //更新用户密码
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> parmas,@RequestHeader("Authorization") String token)
    {

        //检验密码
        String old_Pwd = parmas.get("old_pwd");
        String new_Pwd = parmas.get("new_pwd");
        String re_Pwd = parmas.get("re_pwd");
        if(!StringUtils.hasLength(old_Pwd)||!StringUtils.hasLength(new_Pwd)||!StringUtils.hasLength(re_Pwd)){
            return Result.error("缺失必要参数");
        }
        //判断写入密码与数据库密码一致吗
        Map<String,Object> map= ThreadLocalUtil.get();
        String username=(String) map.get("username");
        User user =userService.findByUserName(username);
        if(!user.getPassword().equals(Md5Util.getMD5String(old_Pwd))){
            return Result.error("原密码不正确");
        }

        //判断两次输入密码
        if(!new_Pwd.equals(re_Pwd)){
            return Result.error("两次密码填写不一致");
        }
        //更新新密码
        userService.updatePwd(new_Pwd);
        //删除redis中对应的token
        ValueOperations<String,String> operations =stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }

}
